//
//  AppendNoonBlanksVC+AppendActivityBottomRow.m
//  PlanDemo
//
//  Created by 在成长开发 on 2025/9/10.
//

#import "CellModel+AppendActivityBottomRow.h"
#import "CellModel.h"

@implementation CellModel (AppendActivityBottomRow)

+ (NSMutableArray *)appendActivityBottomCell {
    NSMutableArray * result = [CellModel fifteenWeek];
    
    // 找到上午
    [self _amAppendRow:result];
    
    
    // 找到下午
    [self _pmAppendRow:result];
    
    return result;
}

+ (void)_amAppendRow:(NSMutableArray *)result {
    CellModel * am;
    for (CellModel * obj in result) {
        if (obj.type == CellType_Fixed && [obj.content isEqualToString:@"上午"]) {
            am = obj;
            break;
        }
    }
    
    if (am == nil) {
        return;
    }
    // 定位行号
    NSInteger lastIndex = [self findNoonLastActivityIndex:result fromNood:am];
    if (lastIndex == -1) {
        return;
    }
    CellModel * lastActivity = [result objectAtIndex:lastIndex];
    NSInteger startRow = lastActivity.row + lastActivity.useRow;
    NSInteger appendRow = kActivityRowStep;
    [self updateCells:result noon:am afterRow:startRow appendRow:appendRow];
    [CellModel createItemsNoMerge:result startRow:startRow appendRow:appendRow];
}

+ (void)_pmAppendRow:(NSMutableArray *)result {
    CellModel * pm;
    for (CellModel * obj in result) {
        if (obj.type == CellType_Fixed && [obj.content isEqualToString:@"下午"]) {
            pm = obj;
            break;
        }
    }
    
    if (pm == nil) {
        return;
    }
    // 定位行号
    NSInteger lastIndex = [self findNoonLastActivityIndex:result fromNood:pm];
    if (lastIndex == -1) {
        return;
    }
    CellModel * lastActivity = [result objectAtIndex:lastIndex];
    NSInteger startRow = lastActivity.row + lastActivity.useRow;
    NSInteger appendRow = kActivityRowStep;
    [self updateCells:result noon:pm afterRow:startRow appendRow:appendRow];
    [CellModel createItemsNoMerge:result startRow:startRow appendRow:appendRow];
}

+ (NSInteger)findNoonLastActivityIndex:(NSMutableArray <CellModel *>*)result fromNood:(CellModel *)noon {
    NSInteger noonEndRow = noon.row + noon.useRow;
    NSInteger lastActivityRow = 0;
    NSInteger lastIndex = -1;
    // 找到上午的最后一行活动行，如果没有就是最后一行文本行
    for (CellModel * obj in result.reverseObjectEnumerator) {
        if (obj.type != CellType_Activity) {
            continue;
        }
        if (obj.row >= noonEndRow || (obj.row < noonEndRow && (obj.row + obj.useRow) > noonEndRow)) {
            continue;
        }
        if (obj.row + obj.useRow <= noon.row) {
            continue;
        }
        
        if (obj.row + obj.useRow > lastActivityRow) {
            lastActivityRow = obj.row + obj.useRow;
            lastIndex = [result indexOfObject:obj];
        }
    }
    return lastIndex;
}



@end
